<template>
  <div>
    <div class="login">
      <div class="login-inform">
        <!-- <div class="name">
          <img src="../../assets/images/login_name.png" alt="" />
        </div> -->
        <div class="login-in">
          <!-- <div class="eyes-box">
            <img v-if="openEyes" src="../../assets/img/img_open_eyes.png" alt="">
            <img v-else src="../../assets/img/img_close_eyes.png" alt="">
          </div> -->
          <div class="title td-fac">
            <span :class="{ active: loginType == 1 }" @click="loginType = 1">登录</span>
            <!-- <span :class="{ active: loginType == 2 }" @click="loginType = 2">快速登录</span> -->
          </div>
          <div class="list">
            <div class="li-l td-f">
              <img :src="$global.Image.icon_mobile" />
              <input
                class="td-f1"
                type="text"
                v-model="account"
                placeholder="输入手机号码"
              />
            </div>
            <div class="li-l td-f" v-if="loginType == 1">
              <img :src="$global.Image.icon_lock" />
              <input
                class="td-f1"
                type="password"
                v-model="password"
                @focus="openEyes = false"
                @blur="openEyes = true"
                placeholder="填写登录密码"
              />
            </div>
            <div class="li-l td-f" v-if="loginType == 2">
              <img :src="$global.Image.icon_message" />
              <input
                class="td-f1"
                type="text"
                v-model="codeVal"
                placeholder="填写验证码"
              />
              <div
                class="code-btn td-fcc"
                :class="{ disabled: timeout != 60 }"
                @click="code"
              >
                {{ code_text }}
              </div>
            </div>
          </div>
          <div style="height:20px"></div>
          <div class="pwd" @click="$router.push('/findPassword')">忘记密码></div>
          <div class="login-go" @click="_submit">登录</div>
          <div class="register" @click="register">立即注册</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { validatorDefaultCatch } from "@utils/dialog";
import attrs, { required, alpha_num, chs_phone } from "@utils/validate";
import cookie from "@utils/store/cookie";
import {
  login,
  loginMobile,
  registerVerify,
  register,
  getCodeApi
} from "@api/user";

export default {
  name: "login",
  data() {
    return {
      loginType: 1,
      code_text: "获取验证码",
      maxTime: 60,
      timeout: 0,
      keyCode: "",
      type: "login",
      account: "",
      password: "",
      codeVal: "",
      openEyes: true
    };
  },
  created() {
    this.timeout = this.maxTime;
    let account = localStorage.getItem('phone')
    if (account) {
      this.account = account
    }
    document.body.style.cssText = "height: auto;overflow:auto";
  },
  mounted() {
    this.getCode();
    document.addEventListener("keyup", this.enterKey);
  },
  methods: {
    // 监听回车
    enterKey(event) {
      const code = event.keyCode
          ? event.keyCode
          : event.which
              ? event.which
              : event.charCode;
      if (code == 13) {
          this._submit();
      }
    },
    // 验证码key
    getCode() {
      getCodeApi()
        .then(res => {
          this.keyCode = res.data.key;
        })
        .catch(res => {
          this.$dialog.error(res.msg);
        });
    },
    // 获取验证
    async code() {
      if (this.timeout != this.maxTime) {
        return false;
      }
      var that = this;
      const { account } = that;
      try {
        await that
          .$validator({
            account: [
              required(required.message("手机号码")),
              chs_phone(chs_phone.message())
            ]
          })
          .validate({ account });
      } catch (e) {
        return validatorDefaultCatch(e);
      }
      await registerVerify({
        phone: that.account,
        type: that.type,
        key: that.keyCode,
        code: that.codeVal
      })
        .then(res => {
          that.$dialog.success(res.msg);
          that.timeFn();
        })
        .catch(res => {
          if (res.data.status === 402) {
            that.codeUrl = `${VUE_APP_API_URL}/sms_captcha?key=${that.keyCode}`;
            that.isShowCode = true;
          }
          that.$dialog.error(res.msg);
        });
    },
    // 60秒倒计时
    timeFn() {
      this.timer = setInterval(() => {
        this.timeout--;
        this.code_text = `${this.timeout}重新获取`;
        if (this.timeout < 1) {
          clearInterval(this.timer);
          this.code_text = "获取验证码";
          this.timeout = this.maxTime;
        }
      }, 1000);
    },
    async _submit() {
      if (this.account == '001') {
        this.account = '15318898206'
        this.password = '123123'
      } else if (this.account == '002') {
        this.account = '18552130511'
        this.password = '123123'
      } else if (this.account == '003') {
        this.account = '15376750572'
        this.password = '123123'
      }
      const { account, password, codeVal } = this;
      let rules = {};
      if (this.loginType == 1) {
        rules = {
          account: [
            required(required.message("账号")),
            attrs.range([5, 16], attrs.range.message("账号")),
            alpha_num(alpha_num.message("账号"))
          ],
          password: [
            required(required.message("密码")),
            attrs.range([6, 16], attrs.range.message("密码")),
            alpha_num(alpha_num.message("密码"))
          ]
        };
      } else {
        rules = {
          account: [
            required(required.message("账号")),
            attrs.range([5, 16], attrs.range.message("账号")),
            alpha_num(alpha_num.message("账号"))
          ],
          codeVal: [
            required(required.message("验证码")),
            attrs.length(4, attrs.length.message("验证码")),
            alpha_num(alpha_num.message("验证码"))
          ]
        };
      }
      try {
        await this.$validator(rules).validate({ account, password, codeVal });
      } catch (e) {
        return validatorDefaultCatch(e);
      }
      let params = {
        account
      };
      if (this.loginType == 1) {
        params.password = password;
        login(params)
          .then(res => {
            if (res.status == 400) {
              this.$dialog.error(res.msg);
            } else {
              let data = res.data
              let expires_time = data.expires_time.substring(0, 19);
              expires_time = expires_time.replace(/-/g, "/");
              expires_time = new Date(expires_time).getTime() - 28800000;
              const datas = {
                token: data.token,
                expires_time: expires_time
              };
              this.$store.commit("LOGIN", datas);
              this.$store.dispatch("USERINFO").then(() => {
                localStorage.setItem('phone', account)
                this.$store.dispatch('CART_NUM')
                this.$router.replace("/");
              });
            }
          })
          .catch(e => {
            this.$dialog.error(e.msg);
          });
      } else {
        params.codeVal = codeVal;

        let mobileParams = {
          phone:'',
          captcha:'',
        }
        mobileParams.phone=params.account
        mobileParams.captcha=params.codeVal
        loginMobile(mobileParams)
                .then(({ data }) => {
                  let expires_time = data.expires_time.substring(0, 19);
                  expires_time = expires_time.replace(/-/g, "/");
                  expires_time = new Date(expires_time).getTime() - 28800000;
                  const datas = {
                    token: data.token,
                    expires_time: expires_time
                  };
                  this.$store.commit("LOGIN", datas);
                  this.$store.dispatch("USERINFO").then(() => {
                    localStorage.setItem('phone', account)
                    this.$router.replace("/");
                  });
                })
                .catch(e => {
                  this.$dialog.error(e.msg);
                });
      }

    },
    /**
     * 注册
     */
    register() {
      this.$router.push("/register");
    },
    /**
     * 找回密码
     */
    findPassword() {
      this.$router.push("/findPassword");
    }
  }
};
</script>

<style scoped  lang="scss" scoped>
$color: #DA213D;
.login {
  background: url("../../assets/images/login.png") no-repeat;
  background-size: 100% 100%;
  width: 100%;
  height: 650px;
  .login-inform {
    width: 1200px;
    display: flex;
    .name {
      img {
        width: 457px;
        height: 233px;
        position: absolute;
        right: 50%;
        margin-top: 200px;
      }
    }
    .login-in {
      position: absolute;
      right: 10%;
      width: 420px;
      height: 420px;
      background-color: rgba(255, 255, 255, 1);
      box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.2);
      margin-top: 115px;
      padding-left: 27px;
      padding-right: 27px;
      box-sizing: border-box;
      .eyes-box{
        height: 130px;
        margin-top: -116px;
        text-align: center;
        img{
          height: 100%;
        }
      }
      .title {
        width: 80%;
        margin: auto;
        color: rgba(0, 0, 0, 0.65);
        font-size: 18px;
        font-family: PingFangSC-Medium;
        padding-top: 32px;
        span {
          border-bottom: solid transparent 2px;
          padding: 0 5px 5px 5px;
          cursor: pointer;
          color: #DA213D;
          font-weight: bold;
        }
        span.active {
          // border-color: #DA213D;
        }
      }
      .list {
        .li-l {
          margin-top: 24px;
          position: relative;
          img {
               width: 20px;
            height: 20px;
            object-fit: contain;
            display: block;
            position: absolute;
            z-index: 2;
          margin: 12px 10px;
          }
          
          input {
            width: 332px;
            height: 40px;
            border-radius: 4px;
            background-color: rgba(255, 255, 255, 1);
            border: 1px solid rgba(217, 217, 217, 1);
            padding-left: 36px;
            font-size: 16px;
            &:focus{
            outline: 0;
            }
            &:-internal-autofill-selected{
background-color:#fff !important;
            } 
          }
          .code-btn {
            font-size: 16px;
            color: #014a97;
            height: 42px;
            width: 130px;
            border-radius: 4px;
            cursor: pointer;
            border: solid #014a97 1px;
            margin-left: 10px;
          }
          .code-btn.disabled {
            color: #999;
          }
          ::placeholder {
            color: #999;
            opacity: 0.25;
          }
        }
        .yzm {
          input {
            width: 235px;
            padding-left: 14px;
          }
          img {
            width: 108px;
            height: 40px;
            margin: 0;
            margin-left: 11px;
          }
        }
      }
      .pwd {
        font-size: 14px;
        color: $color;
        display: flex;
        height: 54px;
        align-items: center;
        justify-content: flex-end;
        padding-right: 25px;
        cursor: pointer;
      }
      .login-go {
        width: 368px;
        height: 48px;
        line-height: 48px;
        text-align: center;
        background: $color;
        color: #fff;
        font-size: 16px;
        cursor: pointer;
        border-radius: 2px;
      }
      .register {
        width: 368px;
        text-align: center;
        color: $color;
        font-size: 16px;
        padding-top: 16px;
        cursor: pointer;
      }
    }
  }
}
</style>
